package com.haier.tv.mic.detect;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.haier.tv.mic.detect.manager.HaierMicManager;
import com.haier.tv.mic.detect.util.LogUtil;
import com.haier.tv.mic.detect.util.Utils;

public class MicAirDetectActivity extends Activity {

    public static final String TAG = "MicAirDetectActivity";
    public boolean isEscToMainActivity = false;
    public Context mContext = null;
    public TextView channel1TextView = null;
    public TextView channel2TextView = null;
    public TextView channel3TextView = null;
    public TextView channel4TextView = null;
    public TextView channelStateTextView = null;
    public MediaPlayer mMediaPlayer ;
    private static final int DETECT_MEDIA_NUM = 0;
    private static final int SUCCESS_MEDIA_NUM = 1;
    private static final int FAIL_MEDIA_NUM = 2;
    private int playMediaNum = DETECT_MEDIA_NUM;
    private int countTime;
    private TextView mCountDownTextView;
    private static final int COUNT_TIME = 5;
    private static final int DEFAULT_BETWEEN_VALUE = 10;

    @SuppressLint("HandlerLeak")
    public Handler mHandler = new Handler(){

        @SuppressLint("HandlerLeak")
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 0x11:
                    if (countTime == COUNT_TIME){
                        mCountDownTextView.setText("");
                        channelStateTextView.setText("正在录音，请稍后");
                        initMediaPlayer();
                        initPlayDetectAudio();
                    }else{
                        mCountDownTextView.setText(String.valueOf(COUNT_TIME - countTime));
                    }
                    break;

                case 0x12: {
                    String chOne = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch0_db", "error");
                    String chTwo = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch1_db", "error");
                    String chThree = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch2_db", "error");
                    String chFour = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch3_db", "error");

                    double one;
                    double two;
                    double three;
                    double four;

                    if (chOne.equalsIgnoreCase("-inf")) {
                        one = Double.NEGATIVE_INFINITY;
                    } else {
                        one = Double.parseDouble(chOne) ;
                    }

                    if (chTwo.equalsIgnoreCase("-inf")) {
                        two = Double.NEGATIVE_INFINITY;
                    } else {
                        two = Double.parseDouble(chTwo) ;
                    }

                    if (chThree.equalsIgnoreCase("-inf")) {
                        three = Double.NEGATIVE_INFINITY;
                    }else {
                        three = Double.parseDouble(chThree);
                    }
                    if (chFour.equalsIgnoreCase("-inf")) {
                        four = Double.NEGATIVE_INFINITY;
                    }else {
                        four = Double.parseDouble(chFour);
                    }

                    float preOne = Settings.System.getFloat(mContext.getContentResolver(),"mic_ch1_db",10);
                    float preTwo = Settings.System.getFloat(mContext.getContentResolver(),"mic_ch2_db",10);
                    float preThree = Settings.System.getFloat(mContext.getContentResolver(),"mic_ch3_db",10);
                    float preFour = Settings.System.getFloat(mContext.getContentResolver(),"mic_ch4_db",10);

                    if (preOne == 10 || preTwo == 10 || preThree == 10 || preFour == 10) {
                        mHandler.sendEmptyMessage(0x13);
                        initPlayFailAudio();
                        return;
                    }

                    if (/*((one < -50) && (two < -50) && (three < -50) && (four < -50)) && */((Math.abs(one) - Math.abs(preOne) > DEFAULT_BETWEEN_VALUE) &&
                            (Math.abs(two) - Math.abs(preTwo) > DEFAULT_BETWEEN_VALUE) && (Math.abs(three) - Math.abs(preThree) > DEFAULT_BETWEEN_VALUE) &&
                            (Math.abs(four) - Math.abs(preFour) > DEFAULT_BETWEEN_VALUE))) {

                        mHandler.sendEmptyMessage(0x01);
                        initPlaySuccessAudio();
                    } else {
                        mHandler.sendEmptyMessage(0x02);
                        initPlayFailAudio();
                    }
                    break;
                }

                case 0x13:
                    channel1TextView.setTextColor(getColor(R.color.red));
                    channel2TextView.setTextColor(getColor(R.color.red));
                    channel3TextView.setTextColor(getColor(R.color.red));
                    channel4TextView.setTextColor(getColor(R.color.red));
                    channelStateTextView.setVisibility(View.VISIBLE);
                    channelStateTextView.setTextColor(getColor(R.color.red));
                    channelStateTextView.setText("麦克风气密性检测异常");
                    break;
                case 0x00:
                    channelStateTextView.setVisibility(View.VISIBLE);
                    channelStateTextView.setTextColor(getColor(R.color.white));
                    channelStateTextView.setText("正在录音，请稍后");
                    break;
                case 0x01:
                    channelStateTextView.setVisibility(View.VISIBLE);
                    channelStateTextView.setTextColor(getColor(R.color.green));
                    channel1TextView.setTextColor(getColor(R.color.green));
                    channel2TextView.setTextColor(getColor(R.color.green));
                    channel3TextView.setTextColor(getColor(R.color.green));
                    channel4TextView.setTextColor(getColor(R.color.green));
                    channelStateTextView.setText("麦克风气密性检测正常");
                    Utils.setProperty("air_mic_test_result","true");
                    mHandler.sendEmptyMessage(0x03);
                    break;
                case 0x02:
                    channel1TextView.setTextColor(getColor(R.color.red));
                    channel2TextView.setTextColor(getColor(R.color.red));
                    channel3TextView.setTextColor(getColor(R.color.red));
                    channel4TextView.setTextColor(getColor(R.color.red));
                    channelStateTextView.setVisibility(View.VISIBLE);
                    channelStateTextView.setTextColor(getColor(R.color.red));
                    channelStateTextView.setText("麦克风气密性检测异常");
                    mHandler.sendEmptyMessage(0x03);
                    break;
                case 0x03:
                {
                    channel1TextView.setVisibility(View.VISIBLE);
                    channel2TextView.setVisibility(View.VISIBLE);
                    channel3TextView.setVisibility(View.VISIBLE);
                    channel4TextView.setVisibility(View.VISIBLE);

                    String chOne = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch0_db", "error");
                    String chTwo = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch1_db", "error");
                    String chThree = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch2_db", "error");
                    String chFour = HaierMicManager.getHaierMicManager().getPropertyString("mic_ch3_db", "error");

                    LogUtil.d(TAG,"chOne =====  " + chOne);

                    double one;
                    double two;
                    double three;
                    double four;

                    if (chOne.equalsIgnoreCase("-inf")) {
                        one = Double.NEGATIVE_INFINITY;
                    } else {
                        one = Double.parseDouble(chOne) ;
                    }

                    if (chTwo.equalsIgnoreCase("-inf")) {
                        two = Double.NEGATIVE_INFINITY;
                    } else {
                        two = Double.parseDouble(chTwo) ;
                    }

                    if (chThree.equalsIgnoreCase("-inf")) {
                        three = Double.NEGATIVE_INFINITY;
                    }else {
                        three = Double.parseDouble(chThree);
                    }
                    if (chFour.equalsIgnoreCase("-inf")) {
                        four = Double.NEGATIVE_INFINITY;
                    }else {
                        four = Double.parseDouble(chFour);
                    }

                    channel1TextView.setText(String.valueOf(one));
                    channel2TextView.setText(String.valueOf(two));
                    channel3TextView.setText(String.valueOf(three));
                    channel4TextView.setText(String.valueOf(four));
                    break;
                }
                case 0x04:
                {
                    isEscToMainActivity = false;
                    finish();
                    break;
                }
                default:break;
            }
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_air_detect);
        mContext = this;
        Intent intent = getIntent();
        Utils.setProperty("air_mic_test_result","false");
        isEscToMainActivity = intent.getBooleanExtra("isBackToMain",false);
        mMediaPlayer = new MediaPlayer();
        initViews();
    }

    private void initPlayDetectAudio() {

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor afd = getAssets().openFd("detect.wav");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); // 设置媒体数据的文件路径
            mMediaPlayer.prepare(); // 媒体播放器准备就绪
            playMediaNum = DETECT_MEDIA_NUM;

        } catch (Exception e) {
            LogUtil.e(TAG,"playRecord error");
        }
    }

    private void initMediaPlayer() {

        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mediaPlayer) {

                LogUtil.d(TAG,"onPrepared");
                if (!mMediaPlayer.isPlaying())
                    mMediaPlayer.start();
                if (playMediaNum == DETECT_MEDIA_NUM){

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.sendEmptyMessage(0x00);
                            HrTvApi.getInstance().beforeMicDetectInit();
                            HaierMicManager.getHaierMicManager().micInit(6,16000);
                        }
                    }).start();
                }
            }
        });

        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {

                if (playMediaNum == DETECT_MEDIA_NUM){
                    HaierMicManager.getHaierMicManager().micDeInit();
                    HaierMicManager.getHaierMicManager().checkMicOk();
                    
                    mHandler.sendEmptyMessageDelayed(0x12,200);

                }else if (playMediaNum == SUCCESS_MEDIA_NUM || playMediaNum == FAIL_MEDIA_NUM){
                    mHandler.sendEmptyMessageDelayed(0x04,5000);
                }
            }
        });
    }

    private void initViews() {
        channel1TextView = (TextView) findViewById(R.id.mic_channel1_state_text_view);
        channel2TextView = (TextView) findViewById(R.id.mic_channel2_state_text_view);
        channel3TextView = (TextView) findViewById(R.id.mic_channel3_state_text_view);
        channel4TextView = (TextView) findViewById(R.id.mic_channel4_state_text_view);
        channel1TextView.setVisibility(View.INVISIBLE);
        channel2TextView.setVisibility(View.INVISIBLE);
        channel3TextView.setVisibility(View.INVISIBLE);
        channel4TextView.setVisibility(View.INVISIBLE);

        channelStateTextView = (TextView) findViewById(R.id.mic_state_text_view);
        channelStateTextView.setText(getString(R.string.str_air_detect_no_pass_note));
        mCountDownTextView = (TextView) findViewById(R.id.mic_count_down_text_view);
        mCountDownTextView.setText(String.valueOf(COUNT_TIME));

        new Thread(new Runnable() {
            @Override
            public void run() {

                while(countTime < COUNT_TIME){

                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException em) {
                        throw new RuntimeException(em);
                    }
                    mHandler.sendEmptyMessageDelayed(0x11,0);
                    countTime++;
                }
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK)
            finish();
        return super.onKeyDown(keyCode, event);
    }

    private void initPlaySuccessAudio(){

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor afd = getAssets().openFd("air_mic_detect_success.wav");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); // 设置媒体数据的文件路径
            mMediaPlayer.prepare(); // 媒体播放器准备就绪
            playMediaNum = SUCCESS_MEDIA_NUM;

        } catch (Exception e) {
            LogUtil.e(TAG,"playRecord error");
        }
    }

    private void initPlayFailAudio(){

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor afd = getAssets().openFd("air_mic_detect_fail.wav");
            mMediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength()); // 设置媒体数据的文件路径
            mMediaPlayer.prepare(); // 媒体播放器准备就绪
            playMediaNum = FAIL_MEDIA_NUM;

        } catch (Exception e) {
            LogUtil.e(TAG,"playRecord error");
        }
    }
}

